﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace Client
{
    public partial class StartClient : Form
    {
        private const int DIM = 1024;
        private String User, Pass, ipVar;

        private UInt16 Porta, ip1Var, ip2Var, ip3Var, ip4Var;
        private IPAddress IPv4;
        private chat myChat;
        private video myVideo;
        private TcpClient sChat, sVideo;
        private String path = Path.Combine(Environment.CurrentDirectory, @".\km_client.conf");
        public delegate void newMessageCallback(string message);

        // Metodi Getter

        public TcpClient getTCP
        {
            get { return sChat; }
        }

        public String getUser
        {
            get { return User; }
        }

        public String getPass
        {
            get { return Pass; }
        }

        public IPAddress getIP
        {
            get { return IPv4; }
        }

        private bool CtrlPort(String tmp)
        {
            if (!tmp.Equals(""))
            {
                try
                {
                    Porta = UInt16.Parse(tmp);
                    if (Porta <= 1025 || Porta > 65535)
                    {
                        MessageBox.Show("Error to insert Port number!\nPlease insert a value between 1025 and 65535!");
                        PortBox.Text = "";
                        return false;
                    }
                }
                catch
                {
                    MessageBox.Show("Error to insert Port number!\nPlease insert a value between 1025 and 65535!");
                    PortBox.Text = "";
                    return false;
                }
                return true;
            }
            else
            {
                MessageBox.Show("Error to insert Port number!\nPlease insert a value between 1025 and 65535!");
                PortBox.Text = "";
                return false;
            }
        }

        private bool CtrlIP(String tmp1, String tmp2, String tmp3, String tmp4)
        {
            bool giusto = true;
            try
            {
                ip1Var = UInt16.Parse(ip1.Text);
                if (ip1Var < 0 || ip1Var > 255)
                {
                    ip1.Text = "";
                    giusto = false;
                }
            }
            catch
            {
                ip1.Text = "";
                giusto = false;
            }

            try
            {
                ip2Var = UInt16.Parse(ip2.Text);
                if (ip2Var < 0 || ip2Var > 255)
                {
                    ip2.Text = "";
                    giusto = false;
                }
            }
            catch
            {
                ip2.Text = "";
                giusto = false;
            }

            try
            {
                ip3Var = UInt16.Parse(ip3.Text);
                if (ip3Var < 0 || ip3Var > 255)
                {
                    ip3.Text = "";
                    giusto = false;
                }
            }
            catch
            {
                ip3.Text = "";
                giusto = false;
            }

            try
            {
                ip4Var = UInt16.Parse(ip4.Text);
                if (ip4Var < 0 || ip4Var > 255)
                {
                    ip4.Text = "";
                    giusto = false;
                }
            }
            catch
            {
                ip4.Text = "";
                giusto = false;
            }

            if (!giusto)
            {
                MessageBox.Show("Error to insert IPv4 address!");
            }

            return giusto;
        }

        public StartClient()
        {
            InitializeComponent();
            if (File.Exists(path))
            {
                using (StreamReader LeggiConf = File.OpenText(path))
                {
                    User = UserName.Text = LeggiConf.ReadLine();
                    String line = LeggiConf.ReadLine();
                    if (line.Equals("ipv4_address"))
                    {
                        ipVar = LeggiConf.ReadLine();
                        IPv4 = IPAddress.Parse(ipVar);
                        String[] ipSlit = ipVar.Split('.');
                        ip1.Text = ipSlit[0]; ip1Var = UInt16.Parse(ip1.Text);
                        ip2.Text = ipSlit[1]; ip2Var = UInt16.Parse(ip2.Text);
                        ip3.Text = ipSlit[2]; ip3Var = UInt16.Parse(ip3.Text);
                        ip4.Text = ipSlit[3]; ip4Var = UInt16.Parse(ip4.Text);
                    }
                    PortBox.Text = LeggiConf.ReadLine();
                }
            }
        }
        
        private void OKButtonClick(object sender, EventArgs e)
        {
            bool manda = true;

            if (UserName.Text.Equals(""))
            {
                MessageBox.Show("Insert an Username!");
                manda = false;
            }
            else
            {
                User = UserName.Text;
            }

            if (Password.Text.Equals(""))
            {
                MessageBox.Show("Insert a Password!");
                manda = false;
            }
            else
            {
                Pass = Password.Text;
            }

            if (CtrlIP(ip1.Text, ip2.Text, ip3.Text, ip4.Text))
            {
                ip1Var = UInt16.Parse(ip1.Text);
                ip2Var = UInt16.Parse(ip2.Text);
                ip3Var = UInt16.Parse(ip3.Text);
                ip4Var = UInt16.Parse(ip4.Text);
                ipVar = ip1Var + "." + ip2Var + "." + ip3Var + "." + ip4Var;
                IPv4 = IPAddress.Parse(ipVar);
            }
            else
            {
                manda = false;
            }

            if (CtrlPort(PortBox.Text))
            {
                Porta = UInt16.Parse(PortBox.Text);
            }
            else
            {
                manda = false;
            }

            if (manda)
            {
                using (StreamWriter ScriviConf = File.CreateText(path))
                {
                    ScriviConf.WriteLine(UserName.Text);
                    ScriviConf.WriteLine("ipv4_address");
                    ScriviConf.WriteLine(ipVar);
                    ScriviConf.WriteLine(PortBox.Text);
                }

                //Manda i dati al server
                //controlli sulla correttezza dei dati mandati
                byte[] tmp = new byte[DIM];
                try
                {
                    sChat = new TcpClient();
                    sChat.Connect(IPv4, Porta);
                    int len = sChat.GetStream().Read(tmp, 0, DIM);
                    String other = System.Text.Encoding.ASCII.GetString(tmp);
                    other = other.Substring(0, len);
                    if (other.Equals("Impossible"))
                    {
                        sChat.Close();
                        MessageBox.Show("Impossible to connect... Try later");
                    }
                    else if (other.Equals("Password"))
                    {
                        byte[] buf = new byte[DIM];
                        sChat.GetStream().Write(Encoding.ASCII.GetBytes(Password.Text), 0, Password.Text.Length);
                        len = sChat.GetStream().Read(buf, 0, DIM);
                        other = System.Text.Encoding.ASCII.GetString(buf);
                        String[] stringa = other.Split('-');
                        if (stringa[0].Equals("OK"))
                        {
                            sVideo = new TcpClient();
                            sVideo.Connect(IPv4, int.Parse(stringa[1]));
                            String user = User;
                            sChat.GetStream().Write(Encoding.ASCII.GetBytes(user.ToCharArray()), 0, user.Length);
                            myChat = new chat(this, stringa[2]);
                            myChat.Show();
                            myVideo = new video(sVideo);
                            myVideo.Show();
                        }
                        else
                        {
                            sChat.Close();
                            MessageBox.Show("Wrong password...");
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("Impossible to connect... Try later");
                }
            }
        }
       
        private void CancelButtoClick(object sender, EventArgs e)
        {
            UserName.Text = "";
            Password.Text = "";
            ip1.Text = "";
            ip2.Text = "";
            ip3.Text = "";
            ip4.Text = "";
            PortBox.Text = "";

        }
        private void ExitButtonClick(object sender, EventArgs e)
        {
            try
            {
                myChat.getSClipCon.GetStream().Close();
                myChat.getSClipCon.Close();
            }
            catch { ; }
            try
            {
                sChat.GetStream().Close();
                sChat.Close();
            }
            catch { ;}
            try
            {
                myVideo.rec_img.Abort();

            }
            catch { ;}
            try
            {
                myChat.recvClip.Abort();
            }
            catch { ;}
            this.Close();
        }
    }
}
